import React from 'react';
import { Input, Form, Select, Checkbox, Button, Cascader, Radio, message } from 'antd';
import GroupInput from '../AddGoods/GroupInput';
import UploadImg from '../../../component/Upload/Upload';
import BraftEditor from '../../../component//BraftEditor/BraftEditor';
import GoodsSpecifications from '../AddGoods/GoodsSpecifications';
import '../AddGoods/AddGoods.css';
import axios from '../../../utils/http';
import { inject, observer } from 'mobx-react';
import Url_To_File from '../../../utils/Url_To_File';
const { Option } = Select;
@inject('addGoodsMobx')
@observer
class ModifyGoods extends React.Component {
  state = {
    groupList: [],
    list: [],
    classList: [],
    labelList: [],
    currentGoods: {
      comspec: [],
      comspecId: '',
      file1: '',
      file2: '',
      file3: '',
      goodsCd: '',
      goodsCi: '',
      goodsCid: '',
      goodsClass: {},
      goodsCstatus: '',
      goodsCode: '',
      goodsCothotr: '',
      goodsCp: '',
      goodsCw: '',
      goodsFss: '',
      goodsId: '',
      goodsIds: '',
      goodsIw: '',
      goodsJj: '',
      goodsLq: '',
      goodsMp: '',
      goodsName: '',
      goodsPp: '',
      goodsPrice: '',
      goodsPx: '',
      goodsRbs: '',
      goodsRemarks: '',
      goodsRs: '',
      goodsSjzt: '',
      gp: [],
      gpId: '',
      pa: [],
      paId: '',
      pll: [],
      pllIds: '',
      pllId: '',
      pllIds: '',
      xnxl: '',
    },
    defaultClass: [],
  };
  componentDidMount = () => {
    this.getCurrentGoodsById(this.props.location.state.id);
    this.props.addGoodsMobx.formChange('goodsId', this.props.location.state.id);
    this.getOneClass();
    this.getAllLabel();
  };
  componentWillUpdate = () => {
    this.myInputRefs = this.refs.form;
  };
  /* 获取当前商品信息 */
  getCurrentGoodsById = id => {
    axios({
      url: '/mm-goods/goods/selGoodsQb',
      method: 'get',
      params: { goodsId: id },
    }).then(({ data }) => {
      console.log(data.data[0]);
      this.setState({
        currentGoods: data.data[0],
      });
      let obj = data.data[0];

      let O = {
        goodsName: obj.goodsName /* 商品名称 */,
        goodsCode: obj.goodsCode /* 商品编号 */,
        goodsJj: obj.goodsJj /* 商品简介 */,
        pllIds: obj.pll.map(item => item.pllId) /* 商品标签 */,
        goodsCothotr: obj.goodsCothotr /* 团长佣金 */,
        goodsLq: obj.goodsLq /* 限购数量 */,
        goodsPrice: obj.goodsPrice /* 商品价格 */,
        goodsCd: obj.goodsCd /* 商品详情 */,
        goodsCw: parseInt(obj.goodsCw.replace(/[^0-9]/gi, '')) /* 商品重量 */,
        goodsC: obj.goodsCw.replace(/[^a-zA-Z]/gi, '') /* 商品重量单位 */,
        goodsCi: obj.goodsCi /* 商品库存 */,
        goodsIw: obj.goodsIw /* 库存警告 */,
        goodsRs: obj.goodsRs /* 加入推荐 */,
        goodsFss: obj.goodsFss /* 免 运 费 */,
        goodsRemarks: obj.goodsRemarks /* 商家备注*/,
        goodsMp: obj.goodsMp,
      };
      this.myInputRefs.setFieldsValue(O);
      obj.gp.some(item => {
        this.addGroup(item);
      });
      obj.comspec.some(item => {
        this.addList(item);
      });
      for (const key in O) {
        if (key === 'comspec') {
          O[key].some(async (item, i) => {
            let base64 = await Url_To_File.urlToBase64(item.pageUrl);
            let file = await Url_To_File.dataURLtoFile(base64, item.pageUrl, item.pageUrl);
            O[key][i].file = file;
          });
        }
        this.props.addGoodsMobx.formChange(key, O[key]);
      }
    });
  };
  /* 确认已选中的份类 */
  sureClasses = obj => {
    let arr = [...this.state.defaultClass];
    arr.push(obj.goodsClass.goodsCid);
    this.setState({
      defaultClass: arr,
    });
  };
  /* 获取一级数据 */
  getOneClass = () => {
    axios({
      url: '/mm-goods/goods/queryGoodsCyi',
    }).then(({ data }) => {
      let arr = data.data.map(item => {
        return {
          value: item.goods_cid,
          label: item.goods_cname,
          isLeaf: false,
        };
      });
      this.setState({
        classList: arr,
      });
    });
  };
  /* 动态加载二级分类数据 */
  loadClass = val => {
    const targetOption = val[val.length - 1];
    targetOption.loading = true;
    let twoClassArr = [];
    // load options lazily
    axios({
      url: '/mm-goods/goods/queryGoodsCer',
      params: {
        goodPid: targetOption.value,
      },
    }).then(({ data }) => {
      if (data.code === 200) {
        twoClassArr = data.data.map(item => {
          return {
            value: item.goods_cid,
            label: item.goods_cname,
            isLeaf: true,
          };
        });
        targetOption.loading = false;
        let arr = this.state.classList.map(item => {
          if (item.value === targetOption.value) {
            item.children = twoClassArr;
          }
          return item;
        });
        this.setState({
          classList: arr,
        });
      }
    });
  };
  /* 获取所有标签 */
  getAllLabel = () => {
    axios({
      url: '/mm-goods/goods/qureyPll',
      method: 'get',
    }).then(({ data }) => {
      let arr = data.data.filter(item => item.pll_statu === 1);
      let newarr = arr.map(item => {
        return { label: item.pll_name, value: item.pll_id };
      });
      this.setState({
        labelList: newarr,
      });
    });
  };
  /* 添加拼团规格 */
  addGroup = o => {
    let list = '';
    if (o) {
      list = {
        id: this.state.groupList.length,
        com: (
          <GroupInput
            delGroup={this.delGroup}
            item={o}
            key={this.state.groupList.length + 1}
            index={this.state.groupList.length}
          />
        ),
      };
    } else {
      list = {
        id: this.state.groupList.length,
        com: (
          <GroupInput
            delGroup={this.delGroup}
            key={this.state.groupList.length + 1}
            index={this.state.groupList.length}
          />
        ),
      };
    }

    let arr = [...this.state.groupList];
    arr.push(list);
    this.setState({
      groupList: arr,
    });
    this.addGps(o);
  };
  addGps = o => {
    if (o) {
      this.props.addGoodsMobx.addGp({
        id: this.state.groupList.length,
        val: {
          gpNogb: o.gpNogb /* 团购人数 */,
          gpPrice: o.gpPrice /* 团购价格 */,
        },
      });
    } else {
      this.props.addGoodsMobx.addGp({
        id: this.state.groupList.length,
        val: {
          gpNogb: '' /* 团购人数 */,
          gpPrice: '' /* 团购价格 */,
        },
      });
    }
  };
  /* 删除拼团规格 */
  delGroup = index => {
    let arr = [...this.state.groupList];
    arr.splice(
      arr.findIndex(item => item.id === index),
      1
    );
    this.setState({
      groupList: arr,
    });
    this.props.addGoodsMobx.delGp(index);
  };
  /* 添加规格 */
  addList = o => {
    let list = '';
    if (o) {
      list = {
        id: this.state.list.length,
        com: (
          <GoodsSpecifications
            item={o}
            delList={this.delList}
            key={this.state.list.length + 1}
            index={this.state.list.length}
          />
        ),
      };
    } else {
      list = {
        id: this.state.list.length,
        com: (
          <GoodsSpecifications
            delList={this.delList}
            key={this.state.list.length + 1}
            index={this.state.list.length}
          />
        ),
      };
    }
    let arr = [...this.state.list];
    arr.push(list);
    this.setState({
      list: arr,
    });
    this.addCom(o);
  };
  addCom = o => {
    if (o) {
      this.props.addGoodsMobx.addComspec({
        id: this.state.list.length,
        val: {
          comspecName: o.comspecName /* 商品规格名称 */,
          number: o.number /* 货号 */,
          space: o.space /* 价格 */,
          inventory: o.inventory /* 库存数量 */,
          pageUrl: o.pageUrl /* 图片 */,
        },
      });
    } else {
      this.props.addGoodsMobx.addComspec({
        id: this.state.list.length,
        val: {
          comspecName: '' /* 商品规格名称 */,
          number: '' /* 货号 */,
          space: '' /* 价格 */,
          inventory: '' /* 库存数量 */,
          file: '' /* 图片 */,
        },
      });
    }
  };
  /* 删除规格 */
  delList = index => {
    let arr = [...this.state.list];
    arr.splice(
      arr.findIndex(item => item.id === index),
      1
    );
    this.setState({
      list: arr,
    });
    this.props.addGoodsMobx.delComspec(index);
  };

  modify = () => {
    this.props.addGoodsMobx.modifyGoods();
    message.success('修改成功');
    this.props.history.push('/Home/ShangPing/GoodsManage/GoodsIndex');
  };
  render() {
    const { formChange } = this.props.addGoodsMobx;
    const radioOptions = [
      { label: '精品', value: 1 },
      { label: '新品', value: 2 },
      { label: '热销', value: 3 },
    ];
    return (
      <div className="addGoods">
        <Form
          ref="form"
          style={{ display: 'flex', justifyContent: 'space-around', marginTop: '20px' }}
        >
          <div className="form_item_box">
            {/* 商品名称 */}
            <Form.Item
              label="商品名称"
              name="goodsName"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              hasFeedback
              style={{ width: '300px' }}
            >
              <Input
                bordered={false}
                allowClear
                onChange={e => formChange('goodsName', e.target.value)}
              />
            </Form.Item>

            {/* 商品编号 */}
            <Form.Item
              label="商品编号"
              name="goodsCode"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              hasFeedback
              style={{ width: '300px' }}
            >
              <Input
                bordered={false}
                allowClear
                onChange={e => formChange('goodsCode', e.target.value)}
              />
            </Form.Item>
            {/* 商品分类 */}
            <Form.Item
              label="商品分类"
              name="goodsCid"
              rules={[
                {
                  required: true,
                },
              ]}
              hasFeedback
              style={{ width: '300px' }}
            >
              <Cascader
                className="classSelect"
                bordered={false}
                options={this.state.classList}
                changeOnSelect
                loadData={this.loadClass}
                onChange={e => formChange('goodsCid', e[e.length - 1])}
                style={{ borderBottom: '1px solid #5F5F61' }}
              />
            </Form.Item>

            {/* 商品简介 */}
            <Form.Item
              label="商品简介"
              name="goodsJj"
              rules={[
                {
                  required: true,
                },
              ]}
              hasFeedback
              style={{ width: '300px' }}
              validateTrigger="onBlur"
            >
              <Input.TextArea
                bordered={false}
                allowClear
                autoSize
                style={{ resize: 'none' }}
                onChange={e => formChange('goodsJj', e.target.value)}
              ></Input.TextArea>
            </Form.Item>

            {/* 商品标签 */}
            <Form.Item
              label="商品标签"
              name="pllIds"
              rules={[
                {
                  required: true,
                  message: '请选择商品标签',
                },
              ]}
              style={{ width: '350px' }}
            >
              <Checkbox.Group
                options={this.state.labelList}
                onChange={e => formChange('pllIds', e)}
                style={{ color: 'white' }}
              />
            </Form.Item>

            {/* 团长佣金 */}
            <Form.Item
              label="团长佣金"
              name="goodsCothotr"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              style={{ width: '300px' }}
            >
              <Input
                bordered={false}
                type="number"
                min={0}
                addonAfter="￥"
                onChange={e => formChange('goodsCothotr', e.target.value)}
              />
            </Form.Item>
            {/* 限购数量 */}
            <Form.Item
              label="限购数量"
              name="goodsLq"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              style={{ width: '300px' }}
            >
              <Input
                type="number"
                min={0}
                addonAfter="0为不限购"
                onChange={e => formChange('goodsLq', e.target.value)}
              />
            </Form.Item>
            {/* 商品价格 */}
            <Form.Item
              label="商品价格"
              name="goodsPrice"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              style={{ width: '300px' }}
            >
              <Input
                bordered={false}
                type="number"
                min={0}
                onChange={e => formChange('goodsPrice', e.target.value)}
              />
            </Form.Item>
            {/* 市场价格 */}
            <Form.Item
              label="市场价格"
              name="goodsMp"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              style={{ width: '300px' }}
            >
              <Input
                bordered={false}
                type="number"
                min={0}
                onChange={e => formChange('goodsMp', e.target.value)}
              />
            </Form.Item>
            {/* 拼团价格 */}
            <Form.Item
              label="拼团价格"
              name="拼团价格"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              style={{ width: '300px' }}
            >
              <div className="group_price">
                <div className="groupHeader">
                  <span>团购人数</span>
                  <span>团购价格</span>
                  <span>操作</span>
                </div>
                <div ref={this.group} className="group">
                  {this.state.groupList.map(item => item.com)}
                </div>
                <Button onClick={this.addGroup} style={{ marginTop: '10px' }} type="primary">
                  添加拼团规则
                </Button>
              </div>
            </Form.Item>
          </div>
          <div className="form_item_box form_item_box2">
            {/* 商品规格 */}
            <Form.Item
              label="商品规格"
              name="商品规格"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
            >
              <div className="group_price">
                <div className="group">
                  <div className="goods">
                    <table ref={this.tr}>
                      <thead style={{ color: 'white' }}>
                        <tr>
                          <td>名称</td>
                          <td>货号</td>
                          <td>价格</td>
                          <td>库存</td>
                          <td>图片</td>
                          <td>操作</td>
                        </tr>
                      </thead>
                      <tbody>{this.state.list.map(item => item.com)}</tbody>
                    </table>
                  </div>
                </div>
                <Button onClick={this.addList} style={{ marginTop: '10px' }} type="primary">
                  添加商品规格
                </Button>
              </div>
            </Form.Item>
            {/* 商品详情 */}
            <Form.Item
              label="商品详情"
              name="商品详情"
              rules={[
                {
                  required: true,
                },
              ]}
              hasFeedback
              style={{ maxWidth: '800px' }}
              validateTrigger="onBlur"
            >
              <BraftEditor
                formChange={formChange}
                value={this.state.currentGoods.goodsCd}
              ></BraftEditor>
            </Form.Item>
            {/* 商品相册 */}
            <Form.Item
              className="groupImg"
              label="商品相册"
              name="商品相册"
              style={{ height: '155px' }}
            >
              <UploadImg
                maxNum={4}
                Size={2}
                type="goodsAlbum"
                values={this.state.currentGoods.pa}
              ></UploadImg>
            </Form.Item>
            <p className="tip_p">注：相册图片大小每个不能超过2MB，最多上传4张</p>
          </div>
          <div className="form_item_box" style={{ maxWidth: '450px' }}>
            {/* 商品重量 */}
            <Form.Item
              label="商品重量"
              name="goodsCw"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              hasFeedback
            >
              <Input
                bordered={false}
                type="number"
                min={0}
                allowClear
                onChange={e => formChange('goodsCw', e.target.value)}
              />
            </Form.Item>
            {/* 商品重量 单位*/}
            <Form.Item
              label="重量单位"
              name="goodsC"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              hasFeedback
            >
              <Select
                defaultValue="Kg"
                style={{ width: '60px', color: 'white' }}
                bordered={false}
                onChange={e => formChange('goodsC', e)}
              >
                <Option value="Kg">Kg</Option>
                <Option value="g">g</Option>
              </Select>
            </Form.Item>
            {/* 商品库存 */}
            <Form.Item
              label="商品库存"
              name="goodsCi"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              style={{ marginBottom: '10px' }}
              hasFeedback
            >
              <Input
                bordered={false}
                type="number"
                min={0}
                allowClear
                onChange={e => formChange('goodsCi', e.target.value)}
              />
            </Form.Item>
            <p className="tip_p">
              注：库存在商品存在货品时为不可编辑状态，库存数值取决于其货品数量
            </p>
            {/* 库存警告 */}
            <Form.Item
              label="库存警告"
              name="goodsIw"
              rules={[
                {
                  required: true,
                  type: 'string',
                },
              ]}
              hasFeedback
            >
              <Input
                bordered={false}
                type="number"
                min={0}
                allowClear
                onChange={e => formChange('goodsIw', e.target.value)}
              />
            </Form.Item>
            {/* 加入推荐 */}
            <Form.Item
              label="加入推荐"
              name="goodsRs"
              rules={[
                {
                  required: true,
                  message: '请选择加入推荐',
                },
              ]}
              style={{ marginBottom: '10px' }}
            >
              <Radio.Group
                options={radioOptions}
                onChange={e => formChange('goodsRs', e.target.value)}
              />
            </Form.Item>
            {/* 免运费 */}
            <Form.Item label="免 运 费 " name="goodsFss" style={{ marginBottom: '10px' }}>
              <Checkbox
                style={{ width: '71px' }}
                onChange={e => formChange('goodsFss', e.target.checked === true ? 1 : 0)}
              >
                是
              </Checkbox>
            </Form.Item>
            <span style={{ color: 'rgb(182, 182, 182)' }}>是否为免运费商品</span>

            {/* 商家备注 */}
            <Form.Item
              label="商家备注"
              name="goodsRemarks"
              hasFeedback
              style={{ width: '300px', marginBottom: '5px' }}
              validateTrigger="onBlur"
            >
              <Input.TextArea
                allowClear
                autoSize
                style={{ resize: 'none' }}
                onChange={e => formChange('goodsRemarks', e.target.value)}
              />
            </Form.Item>
            <span style={{ color: 'rgb(182, 182, 182)' }}>注：仅供商家自己看到的信息</span>
            {/* 商品图片 */}
            <Form.Item
              className="goodsImg"
              label="商品图片"
              name="商品图片"
              style={{ marginBottom: '0px', height: '155px' }}
            >
              <UploadImg
                maxNum={1}
                Size={2}
                type="goodsImg"
                defaultValue={this.state.currentGoods.goodsPp}
              ></UploadImg>
              <p className="tip_p">注：图片大小不能超过2MB</p>
            </Form.Item>
            {/* 拼团图片 */}
            <Form.Item
              className="groupImg"
              label="拼团图片"
              name="拼团图片"
              style={{ height: '155px', marginBottom: '0' }}
            >
              <UploadImg
                maxNum={1}
                Size={2}
                type="spellGroupImg"
                defaultValue={this.state.currentGoods.goodsCp}
              ></UploadImg>
              <p className="tip_p">注：图片大小不能超过2MB</p>
            </Form.Item>
          </div>
        </Form>

        <div style={{ textAlign: 'right', paddingTop: '8px' }}>
          <Button type="primary" onClick={this.modify}>
            提交
          </Button>
        </div>
      </div>
    );
  }
}
export default ModifyGoods;
